package com.wan37.logic.guild.dao.impl;

import com.wan37.logic.guild.dao.GuildDao;
import com.wan37.logic.guild.domain.entity.GuildDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-08-03 17:09
 **/
@Repository
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class GuildDaoImpl implements GuildDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Override
    public boolean add(GuildDO guildDO) {
        hibernateTemplate.save(guildDO);
        return true;
    }

    @Override
    public boolean delete(Integer id) {
        hibernateTemplate.delete(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(GuildDO guildDO) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("update GuildDO set name=?,headerId=?," +
                "level=?,experience=?,notice=? where guildId = ?");
        query.setParameter(0, guildDO.getName());
        query.setParameter(1, guildDO.getHeaderId());
        query.setParameter(2, guildDO.getLevel());
        query.setParameter(3, guildDO.getExperience());
        query.setParameter(4, guildDO.getNotice());
        query.setParameter(5, guildDO.getGuildId());
        query.executeUpdate();
        return true;
    }

    @Override
    public List<GuildDO> getAll() {
        return (List<GuildDO>) hibernateTemplate.find("from GuildDO ");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByGuildId(String guildId) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("delete from GuildDO where guildId=?");
        query.setParameter(0, guildId);
        query.executeUpdate();
        return true;
    }

    @Override
    public List<GuildDO> getGuildDOByGuildId(String guildId){
        return (List<GuildDO>) hibernateTemplate.find("from  GuildDO where guildId = ?", guildId);
    }
}
